<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.title}}</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }
        .nav {
            text-align: center;
            margin-bottom: 30px;
        }
        .nav a {
            display: inline-block;
            margin: 0 10px;
            padding: 8px 16px;
            background: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-size: 14px;
        }
        .nav a:hover {
            background: #5a6268;
        }
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        .search-box {
            display: flex;
            gap: 10px;
        }
        .search-box input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 200px;
        }
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        .btn-primary {
            background: #007bff;
            color: white;
        }
        .btn-primary:hover {
            background: #0056b3;
        }
        .btn-success {
            background: #28a745;
            color: white;
        }
        .btn-success:hover {
            background: #218838;
        }
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        .btn-warning:hover {
            background: #e0a800;
        }
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        .btn-danger:hover {
            background: #c82333;
        }
        .btn-sm {
            padding: 4px 8px;
            font-size: 12px;
        }
        .category-tree {
            border: 1px solid #ddd;
            border-radius: 5px;
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        .tree-item {
            padding: 8px 12px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
        }
        .tree-item:hover {
            background: #f8f9fa;
        }
        .tree-item.level-1 {
            padding-left: 12px;
            font-weight: bold;
        }
        .tree-item.level-2 {
            padding-left: 32px;
        }
        .tree-item.level-3 {
            padding-left: 52px;
        }
        .tree-item.level-4 {
            padding-left: 72px;
        }
        .category-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .category-table th,
        .category-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .category-table th {
            background: #f8f9fa;
            font-weight: bold;
        }
        .category-table tr:hover {
            background: #f8f9fa;
        }
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
            gap: 10px;
        }
        .pagination button {
            padding: 6px 12px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
        }
        .pagination button:hover {
            background: #f8f9fa;
        }
        .pagination button.active {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 20px;
            border-radius: 5px;
            width: 400px;
            max-width: 90%;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .close {
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }
        .close:hover {
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            display: none;
        }
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
        }
        .tab.active {
            border-bottom-color: #007bff;
            color: #007bff;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>{{.title}}</h1>
        
        <div class="nav">
            <a href="/">返回首页</a>
            <a href="/register">用户注册</a>
            <a href="/login">用户登录</a>
        </div>

        <div id="message" class="message"></div>

        <!-- 标签页 -->
        <div class="tabs">
            <div class="tab active" onclick="showTab('tree')">分类树</div>
            <div class="tab" onclick="showTab('list')">分类列表</div>
            <div class="tab" onclick="showTab('search')">搜索分类</div>
        </div>

        <!-- 分类树标签页 -->
        <div id="tree-tab" class="tab-content active">
            <div class="toolbar">
                <h3>分类树结构</h3>
                <button class="btn btn-success" onclick="showCreateModal()">创建分类</button>
            </div>
            <div id="categoryTree" class="category-tree">
                <div style="text-align: center; padding: 40px; color: #999;">
                    点击"刷新分类树"加载数据
                </div>
            </div>
            <div style="text-align: center;">
                <button class="btn btn-primary" onclick="loadCategoryTree()">刷新分类树</button>
            </div>
        </div>

        <!-- 分类列表标签页 -->
        <div id="list-tab" class="tab-content">
            <div class="toolbar">
                <h3>分类列表</h3>
                <div>
                    <button class="btn btn-primary" onclick="loadCategoriesList(1)">刷新列表</button>
                    <button class="btn btn-success" onclick="showCreateModal()">创建分类</button>
                </div>
            </div>
            <table id="categoryTable" class="category-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>分类名称</th>
                        <th>层级</th>
                        <th>路径</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 40px; color: #999;">
                            点击"刷新列表"加载数据
                        </td>
                    </tr>
                </tbody>
            </table>
            <div id="pagination" class="pagination"></div>
        </div>

        <!-- 搜索分类标签页 -->
        <div id="search-tab" class="tab-content">
            <div class="toolbar">
                <div class="search-box">
                    <input type="text" id="searchKeyword" placeholder="输入分类名称搜索...">
                    <button class="btn btn-primary" onclick="searchCategories()">搜索</button>
                </div>
            </div>
            <table id="searchTable" class="category-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>分类名称</th>
                        <th>层级</th>
                        <th>路径</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 40px; color: #999;">
                            输入关键词进行搜索
                        </td>
                    </tr>
                </tbody>
            </table>
            <div id="searchPagination" class="pagination"></div>
        </div>
    </div>

    <!-- 创建/编辑分类模态框 -->
    <div id="categoryModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">创建分类</h3>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <form id="categoryForm">
                <div class="form-group">
                    <label for="categoryName">分类名称:</label>
                    <input type="text" id="categoryName" name="name" required>
                </div>
                <div class="form-group">
                    <label for="parentCategory">父分类:</label>
                    <select id="parentCategory" name="parent_id">
                        <option value="">无（顶级分类）</option>
                    </select>
                </div>
                <div style="text-align: right;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const API_BASE = '/api';
        let currentPage = 1;
        let currentSearchPage = 1;
        let isEditMode = false;
        let editCategoryId = null;

        // 标签页切换
        function showTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // 显示选中的标签页
            document.getElementById(tabName + '-tab').classList.add('active');
            event.target.classList.add('active');
        }

        // 显示消息
        function showMessage(message, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.className = `message ${type}`;
            messageDiv.textContent = message;
            messageDiv.style.display = 'block';
            
            setTimeout(() => {
                messageDiv.style.display = 'none';
            }, 3000);
        }

        // 加载分类树
        async function loadCategoryTree() {
            try {
                const response = await fetch(`${API_BASE}/category/tree`);
                const data = await response.json();
                
                if (data.code === 200) {
                    renderCategoryTree(data.data);
                    loadParentOptions(data.data); // 同时更新父分类选项
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage('加载分类树失败', 'error');
            }
        }

        // 渲染分类树
        function renderCategoryTree(categories) {
            const treeDiv = document.getElementById('categoryTree');
            if (!categories || categories.length === 0) {
                treeDiv.innerHTML = '<div style="text-align: center; padding: 40px; color: #999;">暂无分类数据</div>';
                return;
            }

            let html = '';
            function renderNode(node, level = 1) {
                html += `
                    <div class="tree-item level-${level}" data-id="${node.id}">
                        <span>${node.name}</span>
                        <span style="float: right;">
                            <button class="btn btn-warning btn-sm" onclick="editCategory(${node.id}, '${node.name}')">编辑</button>
                            <button class="btn btn-danger btn-sm" onclick="deleteCategory(${node.id})">删除</button>
                        </span>
                    </div>
                `;
                if (node.children && node.children.length > 0) {
                    node.children.forEach(child => renderNode(child, level + 1));
                }
            }

            categories.forEach(category => renderNode(category));
            treeDiv.innerHTML = html;
        }

        // 加载分类列表
        async function loadCategoriesList(page = 1) {
            try {
                const response = await fetch(`${API_BASE}/category?page=${page}&page_size=10`);
                const data = await response.json();
                
                if (data.code === 200) {
                    renderCategoriesTable(data.data.categories, 'categoryTable');
                    renderPagination(data.data, 'pagination', loadCategoriesList);
                    currentPage = page;
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage('加载分类列表失败', 'error');
            }
        }

        // 搜索分类
        async function searchCategories(page = 1) {
            const keyword = document.getElementById('searchKeyword').value.trim();
            if (!keyword) {
                showMessage('请输入搜索关键词', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/category/search?keyword=${encodeURIComponent(keyword)}&page=${page}&page_size=10`);
                const data = await response.json();
                
                if (data.code === 200) {
                    renderCategoriesTable(data.data.categories, 'searchTable');
                    renderPagination(data.data, 'searchPagination', searchCategories);
                    currentSearchPage = page;
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage('搜索分类失败', 'error');
            }
        }

        // 渲染分类表格
        function renderCategoriesTable(categories, tableId) {
            const tbody = document.querySelector(`#${tableId} tbody`);
            if (!categories || categories.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 40px; color: #999;">暂无数据</td></tr>';
                return;
            }

            let html = '';
            categories.forEach(category => {
                html += `
                    <tr>
                        <td>${category.id}</td>
                        <td>${category.name}</td>
                        <td>${category.level}</td>
                        <td>${category.path || '-'}</td>
                        <td>${new Date(category.created_at).toLocaleString()}</td>
                        <td>
                            <button class="btn btn-warning btn-sm" onclick="editCategory(${category.id}, '${category.name}')">编辑</button>
                            <button class="btn btn-danger btn-sm" onclick="deleteCategory(${category.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tbody.innerHTML = html;
        }

        // 渲染分页
        function renderPagination(data, containerId, loadFunction) {
            const container = document.getElementById(containerId);
            if (data.total_pages <= 1) {
                container.innerHTML = '';
                return;
            }

            let html = '';
            
            // 上一页
            if (data.page > 1) {
                html += `<button onclick="${loadFunction.name}(${data.page - 1})">上一页</button>`;
            }

            // 页码
            for (let i = 1; i <= data.total_pages; i++) {
                if (i === data.page) {
                    html += `<button class="active">${i}</button>`;
                } else {
                    html += `<button onclick="${loadFunction.name}(${i})">${i}</button>`;
                }
            }

            // 下一页
            if (data.page < data.total_pages) {
                html += `<button onclick="${loadFunction.name}(${data.page + 1})">下一页</button>`;
            }

            html += `<span>共 ${data.total} 条记录</span>`;
            container.innerHTML = html;
        }

        // 显示创建分类模态框
        function showCreateModal() {
            isEditMode = false;
            editCategoryId = null;
            document.getElementById('modalTitle').textContent = '创建分类';
            document.getElementById('categoryName').value = '';
            document.getElementById('parentCategory').value = '';
            document.getElementById('categoryModal').style.display = 'block';
            loadCategoryTree(); // 刷新父分类选项
        }

        // 编辑分类
        function editCategory(id, name) {
            isEditMode = true;
            editCategoryId = id;
            document.getElementById('modalTitle').textContent = '编辑分类';
            document.getElementById('categoryName').value = name;
            document.getElementById('categoryModal').style.display = 'block';
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('categoryModal').style.display = 'none';
        }

        // 加载父分类选项
        function loadParentOptions(categories) {
            const select = document.getElementById('parentCategory');
            select.innerHTML = '<option value="">无（顶级分类）</option>';
            
            function addOptions(cats, prefix = '') {
                cats.forEach(cat => {
                    if (!isEditMode || cat.id !== editCategoryId) {
                        select.innerHTML += `<option value="${cat.id}">${prefix}${cat.name}</option>`;
                        if (cat.children && cat.children.length > 0) {
                            addOptions(cat.children, prefix + '　');
                        }
                    }
                });
            }
            
            if (categories && categories.length > 0) {
                addOptions(categories);
            }
        }

        // 删除分类
        async function deleteCategory(id) {
            // 先检查是否有子分类
            try {
                const checkResponse = await fetch(`${API_BASE}/category/check-children/${id}`);
                const checkData = await checkResponse.json();
                
                if (checkData.code === 200 && checkData.data.has_children) {
                    // 有子分类，询问用户是否级联删除
                    if (!confirm('该分类下存在子分类，是否级联删除所有子分类？')) {
                        return; // 用户选择不删除
                    }
                } else if (checkData.code !== 200) {
                    showMessage('检查子分类失败', 'error');
                    return;
                }
                
                // 执行删除操作
                if (!confirm('确定要删除这个分类吗？')) {
                    return;
                }

                try {
                    const response = await fetch(`${API_BASE}/category/${id}`, {
                        method: 'DELETE'
                    });
                    const data = await response.json();
                    
                    if (data.code === 200) {
                        showMessage('删除成功', 'success');
                        loadCategoryTree();
                        loadCategoriesList(currentPage);
                    } else {
                        showMessage(data.message, 'error');
                    }
                } catch (error) {
                    showMessage('删除失败', 'error');
                }
            } catch (error) {
                showMessage('检查子分类失败', 'error');
            }
        }

        // 表单提交
        document.getElementById('categoryForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const name = document.getElementById('categoryName').value.trim();
            const parentId = document.getElementById('parentCategory').value;
            
            if (!name) {
                showMessage('分类名称不能为空', 'error');
                return;
            }

            const requestData = {
                name: name,
                parent_id: parentId ? parseInt(parentId) : null
            };

            try {
                let response;
                if (isEditMode) {
                    response = await fetch(`${API_BASE}/category/${editCategoryId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestData)
                    });
                } else {
                    response = await fetch(`${API_BASE}/category/`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestData)
                    });
                }
                
                const data = await response.json();
                
                if (data.code === 200) {
                    showMessage(isEditMode ? '更新成功' : '创建成功', 'success');
                    closeModal();
                    loadCategoryTree();
                    loadCategoriesList(currentPage);
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage(isEditMode ? '更新失败' : '创建失败', 'error');
            }
        });

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadCategoryTree();
        });

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('categoryModal');
            if (event.target === modal) {
                closeModal();
            }
        }

        // 回车搜索
        document.getElementById('searchKeyword').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchCategories();
            }
        });
    </script>
</body>
</html>
